<template>
  <div class="sourceApplyApproval" v-loading="loading">
    <searchForm class="search-form" :searchFormConfig="searchFormConfig" @search="onClickSearch" @clear="onClickClear"
      ref="searchFormRef" />
    <plainTable :tableData="tableData" :tableConfigData="tableConfigData" :pageInfo="pageInfo"
      @prevPage="handlePrevPage" @nextPage="handleNextPage" />
  </div>
</template>

<script setup>
import plainTable from "@/components/plainTable.vue";
import searchForm from "@/components/searchForm.vue";
import { useDetailOrderQuery } from "@/hooks/index";
import { useUserStore, useSelectOptionsStore } from "@/store/index";
import { getDateAnd7DaysAgo } from "@/utils/index";
import { OPERATE_TYPES } from "@/utils/selectOptions";
import { ref } from "vue";

const { initData, tableData, tableConfigData, searchFormConfig, loading, pageInfo } = useDetailOrderQuery();
const userStore = useUserStore();
const selectOptionsStore = useSelectOptionsStore();
const searchFormRef = ref(null);
const onClickSearch = (form) => {
  initData({
    user_id: form.busiId,
    currency: form.currency,
    type: form.operateType,
    startdata: form?.dateRange[0],
    enddata: form?.dateRange[1],
    platform_order: form.platformOrderId,
    channel_order: form.sourceOrderId,
    merchant_order: form.merchantOrderId,
    status: form.orderStatus,
    page: 1,
    ouser_id: userStore.ouser_id
  })
};

const onClickClear = () => {
  const { today, sevenDaysAgo } = getDateAnd7DaysAgo();
  nextType = {
    currency: "MYR",
    operateType: "1"
  }
  initData({
    ouser_id: userStore.ouser_id,
    currency: selectOptionsStore.currencies[0].value,
    type: OPERATE_TYPES[2].value, // 操作类型：充值
    startdata: sevenDaysAgo.dateStr,
    enddata: today.dateStr,
  });
};

const handlePrevPage = () => {
  if (pageInfo.value.currentPage <= 1) {
    pageInfo.value.currentPage = 1;
    return;
  }
  pageInfo.value.currentPage--;
  initData({
    ouser_id: userStore.ouser_id,
    currency: searchFormRef.value.searchForm.currency,
    type: searchFormRef.value.searchForm.operateType,
    startdata: searchFormRef.value.dateRange[0],
    enddata: searchFormRef.value.dateRange[1],
    page: pageInfo.value.currentPage,
  });
}

const handleNextPage = () => {
  if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
    pageInfo.value.currentPage = pageInfo.value.totalPage;
    return;
  }
  pageInfo.value.currentPage++;
  initData({
    ouser_id: userStore.ouser_id,
    currency: searchFormRef.value.searchForm.currency,
    type: searchFormRef.value.searchForm.operateType,
    startdata: searchFormRef.value.dateRange[0],
    enddata: searchFormRef.value.dateRange[1],
    page: pageInfo.value.currentPage,
  });
}
</script>
<style scoped lang="scss">
.sourceApplyApproval {
  .search-form {
    margin-top: 32px;
    margin-bottom: 32px;
  }
}
</style>
